#include "databasetool.h"
#include <qsqlquery.h>

databaseTool::databaseTool() {}

databaseTool::databaseTool(QString ip, int port, QString dataBaseName, QString userName, QString passWord, QObject *parent):QObject(parent)
{
    isDBok=initializeDataBase(ip,port,dataBaseName,userName,passWord);
}

bool databaseTool::initializeDataBase(QString ip, int port, QString dataBaseName,QString userName, QString passWord)
{
    db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(ip);
    db.setPort(port);
    db.setDatabaseName(dataBaseName);
    db.setUserName(userName);
    db.setPassword(passWord);
    if(db.open()){
        return true;
    }
    return false;
}

const QSqlDatabase* databaseTool::getDb() const
{
    return &db;
}

void databaseTool::setDb(const QSqlDatabase &newDb)
{
    db = newDb;
}

bool databaseTool::getIsDBok() const
{
    return isDBok;
}

void databaseTool::setIsDBok(bool newIsDBok)
{
    isDBok = newIsDBok;
}

QString databaseTool::findPSWforACC(QString acc)
{
    QSqlQuery sqlQuery;
    sqlQuery.prepare("select PassWord from codenestuser Where Account = :acc");
    db.transaction();
    sqlQuery.bindValue(":acc",acc);
    if(sqlQuery.exec()){

        if(sqlQuery.next()){
            db.commit();
            return sqlQuery.value(0).toString();
        }

    }else{


        db.rollback();
    }
    return "";
}

QMap<QString, QString> databaseTool::getUserDetailInformation(QString acc)
{
    QMap<QString,QString> mapResult;
    QSqlQuery sqlQuery;
    sqlQuery.prepare("select isVip,VIP,ID,NAME from codenestuser Where Account = :acc");
    sqlQuery.bindValue(":acc",acc);
    if(sqlQuery.exec()){
        if(sqlQuery.next()){
            mapResult.insert("isVip",sqlQuery.value(0).toString());
            mapResult.insert("VIP",sqlQuery.value(1).toString());
            mapResult.insert("ID",sqlQuery.value(2).toString());
            mapResult.insert("NAME",sqlQuery.value(3).toString());
        }
    }
    return mapResult;
}

